(function($) { 	
	$.fn.extend({ 
		ajaxAction: function(options) { 
		
		var defaults = {
			'manager' : null,
		};
		var o = $.extend(defaults, options);
		
		return this.each(function() {     
	        //if mask is clicked  
	        $(this).bind('click.ajax',function (e) {  
	        	e.preventDefault();
	        	var url = $.convertLinkToObject($(this).attr('href'));
	        	o.manager.request(url.link,url.params,function(response){
	        		if (response.status == "success") {
		            	if (o.manager)
		            		o.manager.loadData();
	        		}
	        	});
	        });
	        

		});
	}
	});
	
})(jQuery);(function($) { 	
	$.fn.dataFilter = function(options) { 
		
		var defaults = {
			manager : null
		};
		var o = $.extend(defaults, options);
		
		return this.each(function() {
			
			function setTextFilter(inputField) {
				if (inputField.attr('value') == "")
					o.manager.removeFilter(inputField.attr('name'));
				else
					o.manager.filter(inputField.attr('name'),inputField.attr('value'));
			}
			
			function setCheckFilter(inputField) {
				if (inputField.is(':checked'))
					o.manager.filter(inputField.attr('name'),inputField.attr('value'));	
				else
					o.manager.removeFilter(inputField.attr('name'));	
			}
			
			$(this).find('input:text,select,input:hidden').each(function(){
				setTextFilter($(this));
				if ($(this).is('select,input:hidden')) {
					$(this).change(function(){
						setTextFilter($(this));
						o.manager.loadData();
					});
				}
				if ($(this).is('input:text')) {
					$(this).keyup(function(){
						setTextFilter($(this));
						o.manager.loadData();
					});
				}
			});
			$(this).find('input:checkbox,input:radio').each(function(){
				setCheckFilter($(this));
				$(this).change(function(){
					setCheckFilter($(this));
					o.manager.loadData();
				});
			});
		});
	}
})(jQuery);(function($) { 
	// util functions
	
	/*
	 * Converts a href link to a link object, with the attributes link and params
	 * 
	 */
	$.convertLinkToObject = function(link) {
		linkSplit = link.split('?');
		var linkObj = {'link':linkSplit[0],'params':{}};
		if (linkSplit.length > 1){
			params_arr = linkSplit[1].split('&');
			for (value in params_arr) {
				param = params_arr[value].split('=');
				linkObj['params'][param[0]] = param[1];
			}
		}
		return linkObj;
	}
	
	
	$.fn.dataManager = function(options) { 
		var defaults = {
			urlData:'../demo/getData.php',
			selectorData:'.data-container',
			fnRequest:null
		};
		var o = $.extend(defaults, options);
		var elem = this;
		
		DataManager = function(domElement) {
			this.urlData = '';
			this.selectorData = '';
			this.filterValues = {};
			// reference to datamaner for callback functions
			var mgr = this;
		    	
			this.request = function(url, data, onSuccess) {
				postData = {};
				postData.json = JSON.stringify(data);
				console.log('request: ' + url);
				console.log('json: ' + postData.json);
				$.ajax({
					type: 'POST',
					url: url, 
					data : postData,
					dataType: "json",
					success: function(data, textStatus) {
						if (onSuccess)
							onSuccess(data);
					}
				});
			}			

			this.loadData = function() {
				var filter = this.filterValues;
				var data = {'filter':this.filterValues};
				
				this.request(
					this.urlData,
					data,
			    	function(response) {
						if (response.html) {
							elem.find(mgr.selectorData).html(response.html);
			    			mgr.triggerEvents(elem.find(mgr.selectorData));
			    		}
			    	}
			    );			    		
		    }
		    	
			this.triggerEvents = function(container) {
				container.find('.action-modal').modalAction({'manager':this});	
				container.find('.action-ajax').ajaxAction({'manager':this});
				container.find('.data-filter').dataFilter({'manager':this});
		    }
		    	
			this.filter = function(name,value) {
				if (!value) 
					return this.filterValues[name];
				this.filterValues[name] = value;
			}
		    	
			this.removeFilter = function(name) {
				delete this.filterValues[name];
			}
		    	
		}
		    
		function getManager() {
			return $(elem).data('DataManager');
		}
		    
		//cant't use this in this.each ;)
		var that = this;
		    
		return this.each(function() {
			if ($(that).data('DataManager'))
				return that;
			var manager = new DataManager();
			if (o.fnRequest)
				manager.request = o.fnRequest;
			manager.urlData = o.urlData;
			manager.selectorData = o.selectorData;
			$(that).data('DataManager',manager);
			manager.triggerEvents($(this));
			manager.loadData();
			return that;
		});
	}
})(jQuery);


(function($) { 	
	$.fn.extend({ 
		editForm: function(options) { 
		
		var defaults = {
			fnSuccess : null
		};
		var o = $.extend(defaults, options);
		
		var editForm = $(this);

        function switchForm(formType) {
        	editForm.find('.form-row').each(function(){
        		if ($(this).is('.form-'+ formType + ', .form-base')) {
        			$(this).fadeIn(500);
        		} else {
        			$(this).hide();
        		}
        	});	
        }
		
			
		return this.each(function() {
			
			
	        $(this).find(".form-switcher").each(function() {
	        	switchForm($(this).val());
	        	$(this).change(function(){
	        		switchForm($(this).val());
	        	});
	        	
	        });
	        
	        $(this).find(".form-multivalue").multiValueField();
	        
	        $(this).find(".form-datepicker").each(function() {
	        	var datePickerField = $(this).find('input:first');
	        	
            	json_attrs = datePickerField.next('input').val();
            	attrs = $.parseJSON(json_attrs);
            	
            	$.datepicker.setDefaults($.datepicker.regional['default']);
            	datePickerField.datepicker(attrs);
	        	
            });
	        
			$(this).submit(function(e) {
				e.preventDefault();
	        	var url = $(this).attr('action');
	        	var form = $(this);
	        	data = {}
	        	$(this).find(':input').each(function() {
	        		if (!$(this).is('[name*=__]')) {
		        		if ($(this).is(':checkbox, :radio')) {
		        			if ($(this).is(':checked'))
		        				data[$(this).attr('name')] = $(this).attr('value');
		        		} else {
		        			data[$(this).attr('name')] = $(this).attr('value');
		        		}
	        		}
	        		
	        	});
	        	o.manager.request(url,data,function(response){
	        		if (response.status == "error") {
	        			html = $(response.html);
	        			form.replaceWith(html);
	        			html.editForm(o);
	        		} else {
	        			if (o.fnSuccess)
	        				o.fnSuccess();
	        		}
	        		
	        	});
			});
		});
	}
});
	
})(jQuery);(function($) { 	
	$.fn.extend({ 
		modalAction: function(options) { 
		
		var defaults = {
			'manager' : null,
			'selectorModal' : '#ModalWindow',
			'selectorMask' : '#Mask',
			'selectorContent' : '.modal-content',
			'selectorClose' : '.close',
			'fnLoaded':null
		};
		var o = $.extend(defaults, options);
		
		var mask = $(o.selectorMask);
		var modal = $(o.selectorModal);
		
		function formSuccess() {
        	if (o.manager)
        		o.manager.loadData();
			closeModalWindow();
		}
		
		function closeModalWindow(e) {
       		//console.log('close modal');
        	//Cancel the link behavior
       		if (e)
       			e.preventDefault();  
        	modal.find('.modal-content').html("");
        	modal.hide();
        	mask.hide().unbind('click.modal');
        	modal.find(o.selectorClose).unbind('click.modal');
        	if (o.manager)
        		o.manager.loadData();
		}
		
		function displayModalWindow() {
			
			
			//Get the screen height and width  
			var maskHeight = $(document).height();  
			var maskWidth = $(window).width();
			
			
			//Set height and width to mask to fill up the whole screen  
			mask.css({'width':maskWidth,'height':maskHeight});  
	        //transition effect           
			mask.fadeTo(500,0.8);
			
			//Get the window height and width  
	       	var winH = $(window).height();  
	       	var winW = $(window).width();
	       	
	       	//Set the popup window to center 
	       	modal.css('height', (winH-100) + "px");
	       	modal.css('top',  $(window).scrollTop() + winH/2-modal.height()/2);  
	       	modal.css('left', winW/2-modal.width()/2);
	       	
	        //transition effect  
	       	modal.fadeIn(1000); 
	        //trigger close button  
	       	modal.find(o.selectorClose).bind('click.modal',closeModalWindow);
	       	mask.bind('click.modal',closeModalWindow);
		}
		
		return this.each(function() {     
	        //if mask is clicked  
	        $(this).bind('click.modal',function (e) {  
	        	e.preventDefault();
	        	var url = $.convertLinkToObject($(this).attr('href'));
	        	displayModalWindow();
	        	o.manager.request(url.link,url.params,function(response){
	        		modal.find(o.selectorContent).html(response.html);
	        		if (o.callbackLoaded)
	        			o.fnLoaded(modal);
	        		modal.find("form").editForm({fnSuccess:formSuccess,manager:o.manager});
	        	});
	        });
	        

		});
	}
	});
	
})(jQuery);(function($) { 	
	$.fn.extend({ 
		multiValueField: function(options) { 

		return this.each(function() {
			var valueField = $(this).find(':hidden');
			var valueList = $(this).find('ul');
			var valueListItem = valueList.find('li');
			valueListItem.remove();
			
			var defaultValues = valueField.val().split(';');
			if (!(defaultValues.length == 1 && defaultValues[0] == "")) {
				for (var i = 0; i< defaultValues.length; i++)
					addValue(defaultValues[i]);
			}
			function refreshValueField() {
				var newValues = new Array();
				valueList.find('input').each(function(){
					newValues.push($(this).val());
				});
				valueField.val(newValues.join(';'));
			}
			
			function addValue(value) {
				newValue = valueListItem.clone();
				newValue.find('input').val(value);
				newValue.find('input').change(function(e){
					refreshValueField();
				});
				newValue.find('a').click(function(e){
					e.preventDefault();
					$(this).parent().remove();
					refreshValueField();
				});
				valueList.append(newValue);	
				refreshValueField();
			}
			
			valueList.sortable({
				handle:".drag_handle",
	            stop:refreshValueField
			});
			
			$(this).find('input[name=__add_value]').click(function(e){
				e.preventDefault();
				var value = $(this).prev().val();
				if (value != '') {
					addValue(value);
					$(this).prev().val("");
				}
					
			});
		});
	}
	});
	
})(jQuery);